package plugins

import (
	"time"

	"github.com/golang-jwt/jwt/v4"
)

type AdminClaims struct {
	Id int `json:"id"`
	jwt.RegisteredClaims
}

func (p *AdminClaims) GetApplicationKey() string {
	return "WSL_123456"
}

// 根据id和当前应用key（加密盐）生成token
func (p *AdminClaims) CreateJWTToken(id int) string {
	appKey := p.GetApplicationKey()
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, &AdminClaims{
		id,
		jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)), // 过期时间，默认24小时
			IssuedAt:  jwt.NewNumericDate(time.Now()),                     // 颁发时间
			NotBefore: jwt.NewNumericDate(time.Now()),                     // 不早于时间
			Issuer:    "WSLGo",                                            // 颁发人
			Subject:   "Admin Token",                                      // 主题信息
		},
	})
	tokenString, _ := token.SignedString([]byte(appKey))
	return tokenString
}

// 解密获取用户信息
func (p *AdminClaims) ParseJWTToken(tokenString string) map[string]interface{} {
	appKey := p.GetApplicationKey()
	result, err := jwt.ParseWithClaims(tokenString, &AdminClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(appKey), nil
	})

	if ve, ok := err.(*jwt.ValidationError); ok {
		if ve.Errors&jwt.ValidationErrorMalformed != 0 {
			//格式错误
			panic(ve)
		} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
			//已过期
			panic(ve)
		} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
			//未生效
			panic(ve)
		}
	}

	if err != nil {
		panic(err)
	} else {
		claims := result.Claims.(*AdminClaims)
		return map[string]interface{}{
			"id": claims.Id,
		}
	}
}
